#! /usr/bin/python
# -*- coding: cp1250 -*-
#sys.path.append(r'C:\AFT\.pylib')

import string, sys, glob, re
import pepe.p_txt.bigtxt as bt
from pepe.glib import findcoldelimiter_line as fcd
#import pepe.p_txt.findcdelimiter as fcd

n = '\x0D\x0A'

def main(ifilemask):
    '''
    Purpose:    Strips blank spaces around delimiters of csv files.
    Syntax:     csv_strip <inp_file_mask>
    Example:    csv_strip test.csv
    '''
    for ifile in glob.glob(ifilemask):
        # 2011-09-12_1918 vp
        #of = open(ifile+'_stripped', 'w')
        of = open('stripped_' + ifile, 'wb')

        lino = 0
        cd = ""

        for line in bt.lines(ifile):

            line = re.sub('\x0D\x0A', '', line)
            line = re.sub('\x0A', '', line)
            line = re.sub('\x0D', '', line)
            
            # find what column delimiter is used 
            if cd == "": cd = fcd(line)

            lino += 1
            cols = string.split(line, cd)
            bare_cols = [string.strip(c) for c in cols]
            of.write(string.join(bare_cols, cd) + n)

        of.close()

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print main.__doc__
    else:
        main(sys.argv[1])

